package com.yc.qunxing.websocket;

import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/ws/{orderId}/{clientType}")
public class WebSocketServerP {

    private static Map<String, Session> passengerSessions = new HashMap<>();
    private static Map<String, Session> driverSessions = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("orderId") String orderId, @PathParam("clientType") String clientType) {
        System.out.println("客户端：" + orderId + " (" + clientType + ") 建立连接");
        if ("passenger".equals(clientType)) {
            passengerSessions.put(orderId, session);
        } else if ("driver".equals(clientType)) {
            driverSessions.put(orderId, session);
        }
    }

    @OnMessage
    public void onMessage(String message, @PathParam("orderId") String orderId, @PathParam("clientType") String clientType) {
        System.out.println("收到来自客户端：" + orderId + " (" + clientType + ") 的信息：" + message);
        // 根据订单ID和客户端类型将消息转发给另一方
        if ("passenger".equals(clientType)) {
            Session driverSession = driverSessions.get(orderId);
            if (driverSession != null && driverSession.isOpen()) {
                sendMessage(driverSession, message);
            }
        } else if ("driver".equals(clientType)) {
            Session passengerSession = passengerSessions.get(orderId);
            if (passengerSession != null && passengerSession.isOpen()) {
                sendMessage(passengerSession, message);
            }
        }
    }

    @OnClose
    public void onClose(Session session, @PathParam("orderId") String orderId, @PathParam("clientType") String clientType) {
        System.out.println("连接断开：" + orderId + " (" + clientType + ")");
        if ("passenger".equals(clientType)) {
            passengerSessions.remove(orderId);
        } else if ("driver".equals(clientType)) {
            driverSessions.remove(orderId);
        }
    }

    private void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}